<?php

namespace app\api\controller\shop;

use app\admin\model\Deviceorder;
use app\admin\model\Deviceslot;
use app\admin\model\Staffdevice;
use app\api\service\DeviceService;
use app\common\controller\Api;

/**
 */
class Device extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    public function detail()
    {
        $device_id =$this->request->param('device_id');
        $deviceModel = new \app\admin\model\Device();
        $device = $deviceModel->where('device_id',$device_id)->find();

        $staffDeviceModel = new Staffdevice();
        $staffDevice = $staffDeviceModel->where('device_id',$device_id)->find();
        $operatorName = "";
        if($staffDevice){

            $userModel = new \app\admin\model\User();
            $user = $userModel->where('id',$staffDevice['user_id'])->find();
            $operatorName  = $user['username']."-".$user['mobile'];
        }

        $device['operatorName'] = $operatorName;
        $this->success('',$device);
    }

    public function active()
    {
        $device_id = $this->request->param('deviceId');
        $city = $this->request->param('city');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $address = $this->request->param('address');
        $name = $this->request->param('deviceName');

        $user = $this->auth->getUser();
        $deviceModel = new \app\admin\model\Device();
        $device = $deviceModel->where('device_id',$device_id)->find();
        if(!$device){
            $this->error("设备不存在，请联系客服");
        }
        if($device['agent_id'] != $user['id']) $this->error("无权激活此设备");

        if($lat == "" || $device_id == '' || $name == ''){
            $this->error('请填写必须要的数据');
        }

        $areas = explode(" ",$city);
        $province = "";
        $area = "";
        $cityName = "";
        if(count($areas) == 3){
            $province = $areas[0];
            $cityName = $areas[1];
            $area = $areas[2];
        }

        $city =
        $db = array();
        $db['device_name'] = $name;
        $db['province'] = $province;
        $db['city'] = $cityName;
        $db['county'] = $area;
        $db['address'] = $address;
        $db['lat'] = $lat;
        $db['lng'] = $lng;


        $deviceModel = new \app\admin\model\Device();
        $deviceModel->where('device_id',$device_id)->update($db);
        $this->success('成功');

    }

    //代理商所有的设备
    public function getAgentDeviceList()
    {
        $keyword = $this->request->param('keyword');
        $status = $this->request->param('status');
        $page = $this->request->param('page');
        $user = $this->auth->getUser();
        $userDeviceModel = new \app\admin\model\Device();
        $type = $this->request->param('type');
        if($type == ''){
            $type = 'agent';
        }

        $where = array();
        if($keyword != ""){
            $where['device_name'] = ['like', '%' . trim($keyword) . '%'];
        }
        if($status != ""){
            if($status == 1){
            }else if($status == 2){
                //在线
                $where['online_status'] = 1;
            }else if($status == 3){
                //离线
                $where['online_status'] = 0;
            }else if($status == 4){
                //未激活
                $where['device_name'] = ['<>', ''];
            }else if($status == 5){
                //故障
                $where['err_status'] = 1;
            }
        }

        if($page != ""){

            if($type == 'agent'){
                $where['agent_id'] = $user['id'];

                $limit = 10;
                $offset = ($page - 1) * $limit;
                $list = $userDeviceModel->where($where)->limit($offset,$limit)->select();

            }else{

                $staffDevice = new Staffdevice();
                $deviceList = $staffDevice->with(['device'])->where($where)->where('user_id',$user['id'])->select();
                $list = array();
                foreach ($deviceList as $key=>$val){
                    $list[] = $val['device'];
                }
            }

            $deviceOrderModel = new Deviceorder();

            $slotModel = new Deviceslot();

            foreach ($list as $key=>$val){
                $price = $deviceOrderModel->where('status','not in',['done','fail'])->whereTime('create_time','today')->where('device_id',$val['device_id'])->sum('price');
                $count = $deviceOrderModel->where('status','not in',['done','fail'])->whereTime('create_time','today')->where('device_id',$val['device_id'])->count('id');
                $slot = $slotModel->where('device_id',$val['device_id'])->where('remain',0)->count('id');
                $list[$key]['total'] = $price;
                $list[$key]['count'] = $count;
                $list[$key]['slot'] = $slot;

            }
        }else{

            $staffModel = new \app\admin\model\Staff();
            $staff = $staffModel->where('user_id',$user['id'])->find();
            if($staff){
                $staffDevice = new Staffdevice();
                $deviceList = $staffDevice->with(['device'])->where($where)->where('user_id',$user['id'])->select();
                $list = array();
                foreach ($deviceList as $key=>$val){
                    $list[] = $val['device'];
                }
            }else{
                $where['agent_id'] = $user['id'];

                $list = $userDeviceModel->where($where)->select();
            }

        }
        foreach ($list as $key=>$val){
            $list[$key]['status'] = "";

            if($val['online_status'] == 1){
                $list[$key]['status'] = "在线";
            }else{
                $list[$key]['status'] = "离线";
            }

            if($val['err_status'] == 1){
                $list[$key]['status'] = "故障";
            }
            if($val['device_name'] == ""){
                $list[$key]['status'] = "未激活";
            }
        }
        $this->success('',$list);
    }

    public function slotList()
    {

        $user = $this->auth->getUser();
        $device_id = $this->request->param('device_id');
        $deviceModel = new \app\admin\model\Staffdevice();

        $device = $deviceModel->where('device_id',$device_id)->find();
        $isOk = -1;

        if($device){
            if($device['agent_id'] == $user['id']){
                $isOk = 1;
            }
            if($device['user_id'] == $user['id']){
                $isOk = 1;
            }
        }else{
            $deviceModel = new \app\admin\model\Device();
            $device = $deviceModel->where('device_id',$device_id)->find();
            if($device['agent_id'] == $user['id']){
                $isOk = 1;
            }
        }

        if($isOk == -1) $this->error("无权操作次设备");
        $deviceSlotModel = new Deviceslot();
        $list = $deviceSlotModel->where('device_id',$device_id)->where('is_show',1)->select();
        $this->success('',$list);
    }


    public function slotList2()
    {

        $user = $this->auth->getUser();
        $device_id = $this->request->param('device_id');
        $show = $this->request->param('show');
        $where = array();
        $where['device_id'] = $device_id;
        if($show != ''){
            $where['is_show'] = $show;
        }

        $deviceSlotModel = new Deviceslot();
        $list = $deviceSlotModel->where($where)->select();
        $this->success('',$list);
    }

    public function setShow()
    {

        $device_id = $this->request->param('device_id');
        $slotNos = $this->request->param('slotNos');
        $status = $this->request->param('status');

        $slotNos = json_decode(htmlspecialchars_decode($slotNos), true);

        $deviceSlotModel = new Deviceslot();
        foreach ($slotNos as $key=>$val){
            $deviceSlotModel->where('device_id',$device_id)->where('slot',$val)->update(['is_show'=>$status]);
        }
        $this->success('成功');
    }

    public function testSlot()
    {

        $user = $this->auth->getUser();
        $device_id = $this->request->param('device_id');
        $slot = $this->request->param('slot');
        $deviceModel = new \app\admin\model\Staffdevice();
        $device = $deviceModel->where('device_id',$device_id)->find();
        $isOk = -1;

        if(!$device){
            $deviceModel = new \app\admin\model\Device();
            $device = $deviceModel->where('device_id',$device_id)->find();
            if($device['agent_id'] == $user['id']){
                $isOk = 1;
            }
        }else{
            if($device['agent_id'] == $user['id']){
                $isOk = 1;
            }
            if($device['user_id'] == $user['id']){
                $isOk = 1;
            }
        }

        if($isOk == -1) $this->error("无权操作次设备");

        //发送货道测试

        $req = array();
        $req['order_no'] = getTestOrderNo();
        $req['slot'] = $slot;
        $req['device_id'] = $device_id;
        $req['user_id'] = $user['id'];


        $deviceService = new DeviceService();
        $deviceService->test($req);
        $this->success('已发送');
    }



    public function deviceSum()
    {

        $user = $this->auth->getUser();

        $deviceModel = new \app\admin\model\Device();

        $staffModel = new \app\admin\model\Staff();
        $staff = $staffModel->where('user_id',$user['id'])->find();
        if($staff){
            $staffDeviceModel = new Staffdevice();
            $total = $staffDeviceModel->where('user_id',$user['id'])->count('id');
            $online = $staffDeviceModel->with(['device'])->where('online_status',1)->count('Device.id');
            $offline = $staffDeviceModel->with(['device'])->where('online_status',0)->count('Device.id');
            $uncount = $staffDeviceModel->with(['device'])->where('device_name',"")->count('Device.id');
            $err = $staffDeviceModel->with(['device'])->where('err_status',1)->count('Device.id');
        }else{
            $total = $deviceModel->where('agent_id',$user['id'])->count('id');
            $online = $deviceModel->where('online_status',1)->count('id');
            $offline = $deviceModel->where('online_status',0)->count('id');
            $uncount = $deviceModel->where('device_name',"")->count('id');
            $err = $deviceModel->where('err_status',1)->count('id');
        }



        $ret = array();
        $ret['total'] = $total;
        $ret['online'] = $online;
        $ret['offline'] = $offline;
        $ret['inactivate'] = $uncount;
        $ret['error'] = $err;


        $this->success('',$ret);

    }


    public function deviceSku()
    {

        $device_id = $this->request->param('device_id');
        $deviceSlotModel = new Deviceslot();
        $list = $deviceSlotModel->with(['good'])->where('device_id',$device_id)->order('slot','asc')->where('is_show',1)->select();

        foreach ($list as $key=>$val){
            $list[$key]['good']['cover'] = cdnurl($val['good']['cover'],true);
        }
        $this->success('',$list);
    }

    public function slotEmpty()
    {
        $device_id = $this->request->param('device_id');
        $selectSlot = $this->request->param('selectSlot');

        $slotNos = json_decode(htmlspecialchars_decode($selectSlot), true);


        error_log("==slotEmpty====".json_encode($slotNos));
        $deviceSlotModel = new Deviceslot();
        $list = $deviceSlotModel->where('good_id',0)->where('device_id',$device_id)->order('slot','asc')->where('is_show',1)->select();

        $newList = array();
        foreach ($slotNos as $k=>$v){
            $isHave = -1;
            foreach ($list as $key=>$val){
                if($v == $val['slot']){
                    $isHave = 1;
                }
            }
            if($isHave == -1){
                $newList[] = $v;
            }
        }
        $newSlotList = $deviceSlotModel->where('device_id',$device_id)->where('slot','in',$newList)->select();
        $newList = array_merge($list,$newSlotList);
        usort($newList, function($a, $b) {
            return $a->slot - $b->slot;
        });


        $this->success('',$newList);
    }

    public function skuSet()
    {
        $device_id = $this->request->param('device_id');
        $deviceSlotModel = new Deviceslot();
        $slotNos = $this->request->param('slotNos');
        $skuId = $this->request->param('skuId');
        $skuPrice = $this->request->param('skuPrice');
        $index = $this->request->param('index');
        $coin = $this->request->param('discount');
        $capacity = $this->request->param('capacity');
        $remain = $this->request->param('remain');
        $onSale = $this->request->param('onSale');

        $deviceSlotModel = new Deviceslot();

        $slotNos = json_decode(htmlspecialchars_decode($slotNos), true);

        foreach ($slotNos as $key=>$val){
            $slot = $deviceSlotModel->where('device_id',$device_id)->where('slot',$val)->find();
            if($slot){
                $db = array();
                $db['remain'] = $remain;
                $db['capacity'] = $capacity;
                $db['coin'] = $coin;
                $db['good_id'] = $skuId;
                $db['price'] = $skuPrice;
                $db['weigh'] = $index;
                $db['create_time'] = time();
                $db['status'] = $onSale;
                $deviceSlotModel->where('id',$slot['id'])->update($db);
            }
        }
        $this->success('成功');
    }

    public function setSale()
    {
        $device_id = $this->request->param('device_id');
        $deviceSlotModel = new Deviceslot();
        $slotNos = $this->request->param('slotNos');
        $status = $this->request->param('status');

        $slotNos = json_decode(htmlspecialchars_decode($slotNos), true);
        foreach ($slotNos as $key=>$val) {
            $slot = $deviceSlotModel->where('device_id', $device_id)->where('slot', $val)->find();
            if ($slot) {
                $deviceSlotModel->where('id',$slot['id'])->update(['status'=>$status]);
            }
        }
        $this->success('成功');

    }

    public function clone()
    {

       $user = $this->auth->getUser();
       $srcDeviceId =  $this->request->param('srcDeviceId');
       $destDeviceId =  $this->request->param('destDeviceId');

       $deviceModel = new \app\admin\model\Device();
       $srcDevice = $deviceModel->where('device_id',$srcDeviceId)->find();
       $destDevice = $deviceModel->where('device_id',$destDeviceId)->find();
       if($srcDevice['agent_id'] != $user['id']) $this->error("无权限操作");
       if($destDevice['agent_id'] != $user['id'])$this->error("无权限操作");

        $deviceSlotModel = new Deviceslot();
        $list = $deviceSlotModel->where('device_id',$srcDeviceId)->select();
        foreach ($list as $key=>$val){
           $dest=  $deviceSlotModel->where('device_id',$destDeviceId)->where('slot',$val['slot'])->find();
           if($dest){
               $deviceSlotModel->where('id',$dest['id'])->update(['remain'=>$val['remain'],'capacity'=>$val['capacity'],'good_id'=>$val['good_id'],'price'=>$val['price'],'coin'=>$val['coin'],'weigh'=>$val['weigh']]);
           }
        }

        $this->success('成功');
    }


    public function fillIndexSum()
    {



        $user = $this->auth->getUser();
        $deviceFillModel = new \app\admin\model\Devicefill();
        $todayCount = $deviceFillModel->whereTime('create_time','today')->count('device_id');

        $staffModel = new \app\admin\model\Staff();
        $staff = $staffModel->where('user_id',$user['id'])->find();
        if($staff){
            $deviceModel = new \app\admin\model\Staffdevice();
            $list = $deviceModel->with(['device','slots'])->where('user_id',$user['id'])->select();
        }else{
            $deviceModel = new \app\admin\model\Device();
            $list = $deviceModel->with(['slots'])->where('agent_id',$user['id'])->select();
        }

        $need = 0;
        foreach ($list as $key=>$val){

            $slotList = $val['slots'];
            $total = 0;
            $remian = 0;
            foreach ($slotList as $k=>$v){
                $total+= $v['capacity'];
                $remian += $v['remain'];
            }
            $percent = 1-$remian/$total;
            if($percent >0.4){
                $need += 1;
            }


        }
        $ret = array();
        $ret['needFillCount'] = $need;
        $ret['fillCountToday'] = $todayCount;


        $this->success('',$ret);
    }

    public function getFillDeviceList()
    {

        $keyword = $this->request->param('keyword');
        $user = $this->auth->getUser();
        $deviceModel = new \app\admin\model\Device();
        $where = array();
        if($keyword != ""){
            $where['device_name'] = ['like', '%' . trim($keyword) . '%'];
        }
        $page = $this->request->param('page');
        $limit = 10;
        $offset = ($page - 1) * $limit;


        $staffModel = new \app\admin\model\Staff();
        $staff = $staffModel->where('user_id',$user['id'])->find();
        if($staff){
            $deviceModel = new \app\admin\model\Staffdevice();
            $newList = $deviceModel->with(['device','slots'])->where('user_id',$user['id'])->limit($offset,$limit)->select();
            $list = array();
            foreach ($newList as $key=>$val){
                $obj = $val['device'];
                $obj['slots'] = $val['slots'];
                $list[] = $obj;
            }



        }else{
            $deviceModel = new \app\admin\model\Device();
            $list = $deviceModel->where($where)->with(['slots'])->where('agent_id',$user['id'])->limit($offset,$limit)->select();
        }

        $need = 0;
        foreach ($list as $key=>$val){

            $slotList = $val['slots'];
            $total = 0;
            $remian = 0;
            $empty = 0;
            $lackCount = 0;
            foreach ($slotList as $k=>$v){
                $total+= $v['capacity'];
                $remian += $v['remain'];
                if($v['remain'] == 0){
                    $empty+= 1;
                }
                $lackCount += $v['capacity']-$v['remain'];
            }
            $percent = 100-$remian/$total*100;
            $percent = intval($percent);
            $list[$key]['lack'] = $percent;
            $list[$key]['empty'] = $empty;
            $list[$key]['lackCount'] = $lackCount;

        }
        $this->success('',$list);
    }
}
